<template>
  <div class="container">
    <Breadcrumb :items="['运营商管理', '运营商站点关联']" />
    <a-card class="general-card" :title="$t('运营商站点关联')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="partnerName" :label="$t('运营商名称')">
                  <a-input
                    v-model="searchForm.partnerName"
                    :placeholder="$t('请输入运营商名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="stationName" :label="$t('站点名称')">
                  <a-input
                    v-model="searchForm.stationName"
                    :placeholder="$t('请输入站点名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="relationType" :label="$t('关联类型')">
                  <a-select
                    v-model="searchForm.relationType"
                    :placeholder="$t('请选择关联类型')"
                    allow-clear
                  >
                    <a-option :value="RelationTypeEnum.NORMAL">普通关联</a-option>
                    <a-option :value="RelationTypeEnum.EXCLUSIVE">独家代理</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                  <a-button type="primary" status="success" @click="openAddForm">
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('新增关联') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="运营商名称" data-index="partnerName" />
          <a-table-column title="联系人" data-index="contactName" />
          <a-table-column title="联系电话" data-index="contactPhone" />
          <a-table-column title="站点名称" data-index="stationName" />
          <a-table-column title="站点地址" data-index="stationAddress" :width="180" />
          <a-table-column title="充电桩数量" data-index="pileCount" />
          <a-table-column title="关联类型" data-index="relationTypeName">
            <template #cell="{ record }">
              <a-tag 
                :color="record.relationType === RelationTypeEnum.EXCLUSIVE ? 'purple' : 'blue'"
              >
                {{ record.relationTypeName }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{ formatDateTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="100">
            <template #cell="{ record }">
              <a-button type="text" status="danger" size="small" @click="confirmDelete(record)">
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增关联表单对话框 -->
    <a-modal
      v-model:visible="formVisible"
      title="新增运营商站点关联"
      :width="500"
      @before-ok="handleSubmitForm"
      unmount-on-close
    >
      <partner-station-form ref="formRef" />
      <template #footer>
        <a-space>
          <a-button @click="formVisible = false">取消</a-button>
          <a-button type="primary" @click="submitForm">
            确定
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { 
  getPartnerStationList, 
  removePartnerStation,
  PartnerStation,
  PartnerStationParams,
  RelationTypeEnum
} from '@/api/partnerStation';
import dayjs from 'dayjs';
import { IconSearch, IconRefresh, IconPlus } from '@arco-design/web-vue/es/icon';
import PartnerStationForm from './components/partner-station-form.vue';

const { loading, setLoading } = useLoading();
const renderData = ref<PartnerStation[]>([]);
const formRef = ref();
const formVisible = ref(false);

// 搜索表单
const searchForm = reactive<PartnerStationParams>({
  partnerName: '',
  stationName: '',
  relationType: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 分页
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 格式化日期时间
function formatDateTime(date: string | undefined) {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

// 查询数据
async function fetchData() {
  setLoading(true);
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    
    const res = await getPartnerStationList(params);
    renderData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (err) {
    console.error('获取运营商站点关联列表出错:', err);
    Message.error('获取运营商站点关联列表失败');
  } finally {
    setLoading(false);
  }
}

// 打开新增表单
function openAddForm() {
  formVisible.value = true;
}

// 确认删除
function confirmDelete(record: PartnerStation) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除运营商 "${record.partnerName}" 与站点 "${record.stationName}" 的关联吗？此操作不可恢复。`,
    onOk: async () => {
      try {
        await removePartnerStation(record.id);
        Message.success('删除成功');
        fetchData();
      } catch (err) {
        console.error('删除失败:', err);
        Message.error('删除失败');
      }
    },
  });
}

// 提交表单
async function handleSubmitForm(done: any) {
  try {
    if (!formRef.value) {
      console.error('表单引用不存在');
      Message.error('表单引用不存在');
      done(false);
      return;
    }
    
    const valid = await formRef.value.validate();
    
    if (valid) {
      const result = await formRef.value.submit();
      
      if (result) {
        Message.success('添加关联成功');
        formRef.value.resetForm();
        fetchData();
        done();
      } else {
        Message.error('添加关联失败');
        done(false);
      }
    } else {
      Message.warning('表单验证未通过，请检查表单内容');
      done(false);
    }
  } catch (err) {
    console.error('提交表单出错:', err);
    Message.error('添加关联失败');
    done(false);
  }
}

// 手动提交表单
async function submitForm() {
  try {
    if (!formRef.value) {
      Message.error('表单引用不存在');
      return;
    }
    
    const valid = await formRef.value.validate();
    
    if (valid) {
      const result = await formRef.value.submit();
      
      if (result) {
        Message.success('添加关联成功');
        formVisible.value = false;
        formRef.value.resetForm();
        fetchData();
      } else {
        Message.error('添加关联失败');
      }
    } else {
      Message.warning('表单验证未通过，请检查表单内容');
    }
  } catch (err) {
    console.error('手动提交出错:', err);
    Message.error('提交失败，请检查表单');
  }
}

// 搜索
function search() {
  pagination.current = 1;
  fetchData();
}

// 重置
function reset() {
  searchForm.partnerName = '';
  searchForm.stationName = '';
  searchForm.relationType = undefined;
  pagination.current = 1;
  fetchData();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.general-card {
  :deep(.arco-card-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
  }
}
</style> 